<?php


namespace App\Activity\Service\Free;


use App\Activity\Model\ActivityModel;
use App\Order\Model\OrderGoodsModel;
use App\Common\Constants\Stakeholder;
use App\Order\Model\OrderModel;
use App\Resource\Model\GoodsListModel;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Kernel\Support\Collection;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use App\User\Service\MemberService;
use Psr\Http\Message\ResponseInterface;
use App\Common\Service\MiniAppService;

class FreeMiniService extends FreeBaseService implements FreeServiceInterface
{

    /**
     * @Inject()
     * @var MemberService
     */
    protected MemberService $memberService;
    /**
     * 获取免单活动
     *
     * @param $shop_id
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object|array
     * @author mengchenchen
     */
    public function getFreeOrderActivity($shop_id)
    {
        $date = date('Y-m-d H:i:s');
        $activity = ActivityModel::whereIn('status', [1, 2])
                                 ->where('begin_date', '<', $date)
                                 ->where('end_date', '>', $date)
                                 ->where('is_deleted', '<>', 1)
                                 ->where('activityType', 5)
                                 ->whereRaw('FIND_IN_SET(' . $shop_id . ',shop_ids)')
                                 ->orderBy('begin_date', 'asc')
                                 ->first();
        if (!$activity) {
            return [];
        }
        return [
            'id'    => $activity['activityID'],
            'cover' => $activity['image'],
        ];
    }

    /**
     * 免单活动详情
     * @param $id
     * @return array
     * @author mengchenchen
     */
    public function detail($id)
    {
        $mid = $this->getCurrentInfo() ?: 0;
        $filed = ['activityID', 'activity_prams', 'image', 'status', Db::raw('0 as success_member_number')];
        $activity = ActivityModel::find($id, $filed);
        if (!$activity || !in_array($activity->status, [1, 2])) {
            return ['code' => 0, 'msg' => '活动已结束或已被禁用'];
        }
        $filed = ['id', 'goods_id', 'goods_title', 'goods_logo', 'price_selling', 'free_num'];
        // 活动商品列表
        $goodsList = $activity->activityGoods()->get($filed);
        // 活动商品的订单
        $orderGoodsNos = OrderGoodsModel::whereIn('activity_goods_id', $goodsList->pluck('id'))->pluck('order_no');
        // 商品扩展信息
        $goodsInfo = GoodsListModel::whereIn('goods_id', $goodsList->pluck('goods_id'))->get()->keyBy('goods_id');
        // 截单自提时间
        $takeDate = $this->getOverNightTakeDate();
        // 免单成功列表
        $func = function ($q) use ($orderGoodsNos) {
            $q->where('is_freed', 2)->whereIn('o.order_no', $orderGoodsNos);
        };
        $_freeSuccessList = $this->freeOrderList($func, 'o.order_no,o.is_freed,og.activity_goods_id,m.nickname,m.face_url,og.goods_title,ag.price_selling,o.is_freed,o.pay_at');
        $freeSuccessList = collect($_freeSuccessList)->groupBy(['activity_goods_id']);
        // 我参加发起过的免单成功列表
        $initOrder = $this->freeOrderList(fn($q) => $q->whereRaw("o.mid = $mid and o.is_pay = 1 and o.free_parent_order_no = ''"), 'o.order_no,og.activity_goods_id');
        $initOrder = $initOrder->keyBy('activity_goods_id')->toArray();
        foreach ($goodsList as &$v) {
            $v['goods_pick_time'] = $takeDate . ' ' . substr($goodsInfo[$v['goods_id']]['goods_pick_time'], 0, 5);
            $v['free_success_number'] = count($freeSuccessList[$v['id']] ?? []) + $v['free_num'];
            $activity['success_member_number'] += $v['free_success_number'];
            $v['is_init'] = boolval($initOrder[$v['id']] ?? 0);
        }
        $activity['activity_params'] = json_decode($activity->activity_prams, true);
        unset($activity->activity_prams);
        $activity['goods_list'] = $goodsList;
        $activity['success_list'] = array_values($_freeSuccessList->toArray());
        return ['code' => 1, 'data' => $activity->toArray()];
    }

    /**
     * 免单列表
     *
     * @param $where
     * @param string $filed
     * @param int $limit
     * @return \Hyperf\Utils\Collection
     */
    public function freeOrderList($where, $filed = '*', $limit = 0)
    {
        $list = Db::table('store_order as o')
                  ->selectRaw($filed)
                  ->leftJoin('store_order_goods as og', 'og.order_no', '=', 'o.order_no')
                  ->leftJoin('store_member as m', 'm.mid', '=', 'o.mid')
                  ->leftJoin('store_activity_goods as ag', 'ag.id', '=', 'og.activity_goods_id')
                  ->where($where)
                  ->where('o.order_type', 10);
        if ($limit) {
            $list->limit($limit);
        }
        return $list->get();
    }

    /**
     * 业务场景 获取活动商品单条条目
     * @author ran
     * @date 2021-03-23 16:27
     * mailbox 466180170@qq.com
     */
    public function getFreeActivityGoodsfirstById(int $id,array $exceptKey=[]):array
    {
        $needExceptKey=['goods_cate','mini_app_code','number_sales','per_can_buy_num','click_num','number_virtual'];
        $where =['store_activity_goods.id'=>$id];
        $extraCondition =['where'=>$where];
        return $this->getFreeActivityCommonGoodsfirst(array_merge($needExceptKey,$exceptKey),$extraCondition);
    }

    /**
     * 业务场景 获取免单活动信息
     * @author ran
     * @date 2021-03-23 16:27
     * mailbox 466180170@qq.com
     */
    public function getFreeActivityInfofirstById(int $id,array $exceptKey=[]):array
    {
        $needExceptKey=['id','goods_cate','title','logo','goods_spec','activity_price_market','activity_price_selling','activity_number_stock','spell_num','group_id','commission','need_invited_num','current_cost_price','per_can_buy_num','click_num','mini_app_code'];
        $where =['store_activity_goods.id'=>$id];
        $extraCondition =['where'=>$where];
        return $this->getFreeActivityInfoCommonfirstById(array_merge($needExceptKey,$exceptKey),$extraCondition);
    }

    /**
     * 免单状态
     * @param int $mid
     * @return array|int|mixed
     * @author wangchenqi
     */
    public function getFreeStatus($mid)
    {
        $order_no = OrderModel::query()
            ->where('free_step','!=',5)
            ->where([
                'mid' => $mid,
                'order_source' => Stakeholder::NEXT_DAY_ORDER,
                'order_type' => Stakeholder::ORDER_TYPE_FREE,
                'is_pay' => Stakeholder::ORDER_PAID,
            ])
            ->select('order_no')
            ->first();
        $fail_order_no = OrderModel::query()
            ->where([
                'mid' => $mid,
                'order_source' => Stakeholder::NEXT_DAY_ORDER,
                'order_type' => Stakeholder::ORDER_TYPE_FREE,
                'is_pay' => Stakeholder::ORDER_PAID,
                'is_freed' => 3
            ])
            ->select('order_no')
            ->first();

        if($fail_order_no){
            $fail_order_no['status'] = 2;
            return ['code' => 400, 'data' => $fail_order_no];
        }elseif ($order_no){
            $order_no['status'] = 1;
            return ['code' => 200, 'data' => $order_no];
        }
        return [];
    }
    /**
     * 免单开始订阅通知
     * @param object $orderInfo
     * @return array|Collection|object|ResponseInterface|string
     * @throws GuzzleException
     * @throws InvalidArgumentException
     * @throws InvalidConfigException
     * @author ran
     * @date 2021-03-31 11:02
     * mailbox 466180170@qq.com
     */
    public function freeStartMessage(object $orderInfo){
        $activity_time = ActivityModel::query()->where(['activityID'=>$orderInfo->activity_id])->select(['begin_date','end_date'])->first()->toArray();
        $goods_name = OrderGoodsModel::query()->where(['order_no'=>$orderInfo->order_no])->value('goods_title');
        $template_id = MiniAppService::FREE_START;
        $page = "follow/pages/my-free/my-free";
        $map = [
            "phrase1" => [
                "value" => "赶快邀请吧"
            ],
            "thing2"  => [
                "value" => mb_convert_encoding(substr_replace($goods_name, '...', 30), 'UTF-8')
            ],
            "time3" => [
                "value" => $activity_time['begin_date'].'~'.$activity_time['end_date']
            ],
            "thing4" => [
                "value" => "恭喜您，已成功参与免单活动"
            ],
        ];
        $data = $this->getFreeCommonMessageSend($orderInfo->openid, $template_id, $page, $map);
        $this->writeLogs('App\Activity\Service\Free','参与免单活动日志',json_encode($data));
        return $data;
    }

    /**
     * 免单成功订阅通知
     * @param $order_no
     * @return array|Collection|object|ResponseInterface|string
     * @throws GuzzleException
     * @throws InvalidArgumentException
     * @throws InvalidConfigException
     * @author ran
     * @date 2021-03-31 11:02
     * mailbox 466180170@qq.com
     */
    public function freeMessage($order_no){
        $goods_name = OrderGoodsModel::query()->where(['order_no'=>$order_no])->value('goods_title');
        $openid = OrderModel::query()->where(['order_no'=>$order_no])->value('openid');
        $template_id = MiniAppService::FREE_SUCCEED;
        $page = "follow/pages/my-free/my-free";
        $map = [
            "phrase1" => [
                "value" => "免单成功"
            ],
            "thing2"  => [
                "value" => mb_convert_encoding(substr_replace($goods_name, '...', 30), 'UTF-8')
            ],
            "thing3" => [
                "value" => "恭喜您，已成功免单"
            ],
            "time4" => [
                "value" => date('Y-m-d H:i:s')
            ],
        ];
        $data = $this->getFreeCommonMessageSend($openid, $template_id, $page, $map);
        $this->writeLogs('App\Activity\Service\Free','成功免单日志',json_encode($data));
        return $data;
    }

    /**
     * 免单活动失败
     * @param $order_no
     * @return array|Collection|object|ResponseInterface|string
     * @throws InvalidArgumentException
     * @throws InvalidConfigException
     * @throws GuzzleException
     * @author ran
     * @date 2021-03-31 11:01
     * mailbox 466180170@qq.com
     */
    public function freeFailMessage($order_no){
        $goods_name = OrderGoodsModel::query()->where(['order_no'=>$order_no])->value('goods_title');
        $openid = OrderModel::query()->where(['order_no'=>$order_no])->value('openid');
        $template_id = MiniAppService::FREE_FAIL;
        $page = "follow/pages/my-free/my-free";
        $map = [
            "thing1" => [
                "value" => "彻底失败"
            ],
            "thing2"  => [
                "value" => mb_convert_encoding(substr_replace($goods_name, '...', 30), 'UTF-8')
            ],
            "thing3" => [
                "value" => "很遗憾您参与免单活动失败了"
            ],
            "time4" => [
                "value" => date('Y-m-d H:i:s')
            ],
        ];
        $data = $this->getFreeCommonMessageSend($openid, $template_id, $page, $map);
        $this->writeLogs('App\Activity\Service\Free','免单活动失败日志',json_encode($data));
        return $data;
    }

    /**
     * 变更免单状态   支付成功 $count = 1  二次激活 $count = 2
     * @param $order_no
     * @param int $count
     */
    public function freeOrderStatus($order_no, int $count){
        $this->updateCommonFreeOrderStatus($order_no,$count);
    }
}
